import path from 'path'
import koaBody from "koa-body";
import { cwd } from 'node:process';
import { config } from '../../config';
import fs from "fs/promises";

const router: Api = new Map()

router.set('/upload', [koaBody({
    multipart: true, //支持图片文件
    formidable: {
        maxFileSize: 1024 * 1024 * 2,
        uploadDir: path.join(cwd(), '/public/uploads'), //设置上传目录
        keepExtensions: true, //保留拓展名
    }
}), async (ctx, next) => {
    let file = ctx.request.files?.file   //ctx.request.files.file中的file需要与前端使用的名称保持一致
    if (!file) return
    if (!Array.isArray(file)) {
        file = [file]
    }
    //图片迁移到其他服务器
    let promises = file.map(async item => {
        const file = await fs.readFile(path.join(cwd(), `/public/uploads/${path.basename(item?.filepath || '')}`))
        const form = new FormData()
        const _file = new File([file], path.basename(item?.filepath || ''), { type: 'image/*' });
        form.append('file', _file)
        const res = await fetch(config.BASEURL + '/api/v1/upload/upload', {
            method: 'POST',
            body: form
        })
        const data = await res.json()
        const { errorCode } = data;
        if (!errorCode) {
            return data.url;
        } else {
            return 'error';
        }
    })
    let basename: string | string[] = await Promise.all(promises)
    //不需要迁移时使用
    // const basename = file.map(item => {
    //     return path.join(cwd(), `/public/uploads/${path.basename(item?.filepath || '')}`)
    // })
    if (basename.length === 1) basename = basename[0]
    ctx.body = {
        url: basename
    }
}])

export { router }